//
//  MSRequestOperation.m
//  testMasory
//
//  Created by xiangbo on 2018/9/7.
//  Copyright © 2018年 xiangbo. All rights reserved.
//

#import "MSRequestOperation.h"
#import <AFNetworking.h>
#import <NSObject+YYModel.h>

@implementation MSRequestOperation

+(void)GET:(NSString *)url params:(NSDictionary *)params classType:(Class)classType completion:(MSCompletionBlock)completion{
    [self GET:url params:params headers:nil classType:classType completion:completion];
}

+ (void)GET:(NSString *)url params:(NSDictionary *)params headers:(NSDictionary *)headers classType:(Class)classType completion:(MSCompletionBlock)completion{
    [self requestWithMethod:@"GET" url:url headers:headers params:params classType:classType completion:completion];
}

+(void)POST:(NSString *)url params:(NSDictionary *)params classType:(Class)classType completion:(MSCompletionBlock)completion{
    [self POST:url params:params headers:nil classType:classType completion:completion];
}

+(void)POST:(NSString *)url params:(NSDictionary *)params headers:(NSDictionary *)headers classType:(Class)classType completion:(MSCompletionBlock)completion{
    [self requestWithMethod:@"POST" url:url headers:headers params:params classType:classType completion:completion];
}

+(void)requestWithMethod:(NSString *)method url:(NSString *)url headers:(NSDictionary *)headers params:(NSDictionary *)params classType:(Class)classType completion:(MSCompletionBlock)completion{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    if (headers) {
        for (NSString *key in headers.allKeys) {
            [manager.requestSerializer setValue:headers[key] forHTTPHeaderField:key];
        }
        
    }
    
    void(^SuccessBlock)(NSURLSessionDataTask *,id) = ^(NSURLSessionDataTask *task, id responseObject) {
        [MSRequestOperation requestResponseSuccess:task response:responseObject classType:classType completion:completion];
    };
    
    void(^FailureBlock)(NSURLSessionDataTask *, NSError *) = ^(NSURLSessionDataTask *task, NSError *error) {
        if (completion) {
            completion(task,nil,error);
        }
    };
    
    if ([method.uppercaseString isEqualToString:@"GET"]) {
        [manager GET:url parameters:params progress:nil success:SuccessBlock failure:FailureBlock];
    }else if ([method.uppercaseString isEqualToString:@"POST"]){
        [manager POST:url parameters:params progress:nil success:SuccessBlock failure:FailureBlock];
    }
}

+ (void)requestResponseSuccess:(NSURLSessionDataTask *)task response:(id)response classType:(Class)classType completion:(MSCompletionBlock)completion{
    if (completion) {
        id mapped = [classType modelWithJSON:response];
        completion(task,mapped,nil);
    }
}

@end
